#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
新鲜需求发现小助手演示脚本
演示如何使用新鲜需求发现功能
"""

import sys
import os
import time
from datetime import datetime

# 添加src目录到Python路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))

from src.fresh_topic_discovery import FreshTopicDiscovery, FreshTopicDiscoveryScheduler
from src.utils import load_config, get_logger


def demo_single_discovery():
    """演示单次发现功能"""
    print("🎯 演示单次新鲜需求发现")
    print("=" * 60)
    
    try:
        # 加载配置
        config = load_config()
        
        # 创建发现小助手
        discovery = FreshTopicDiscovery(config)
        
        # 种子关键词
        seed_keywords = [
            "Python编程",
            "数据分析", 
            "机器学习",
            "朋友圈营销"
        ]
        
        print(f"种子关键词: {seed_keywords}")
        print(f"扩展字符: {discovery.expansion_chars}")
        print(f"预计扩展后关键词数量: {len(seed_keywords) * (1 + len(discovery.expansion_chars))}")
        print()
        
        # 运行发现周期
        print("🚀 开始运行发现周期...")
        start_time = time.time()
        
        result = discovery.run_discovery_cycle(seed_keywords, auto_notify=False)
        
        end_time = time.time()
        print(f"⏱️  发现周期耗时: {end_time - start_time:.2f} 秒")
        
        # 显示结果
        if 'error' not in result:
            print("\n📊 发现结果统计:")
            print(f"  种子关键词数量: {result['total_seed_keywords']}")
            print(f"  扩展后关键词数量: {result['total_expanded_keywords']}")
            print(f"  发现新鲜话题: {result['new_topics_found']} 个")
            print(f"  发现耗时: {result['discovery_time']:.2f} 秒")
            
            if result['new_topics_found'] > 0:
                print("\n🎉 发现新鲜话题！建议发送邮件通知用户。")
            else:
                print("\n😔 未发现新鲜话题，可能所有话题都已存在。")
        else:
            print(f"\n❌ 发现周期执行失败: {result['error']}")
        
        # 获取统计信息
        stats = discovery.get_discovery_statistics()
        print(f"\n📈 系统统计信息:")
        for key, value in stats.items():
            print(f"  {key}: {value}")
        
        # 清理资源
        discovery.cleanup()
        
    except Exception as e:
        print(f"❌ 演示失败: {e}")
        import traceback
        traceback.print_exc()


def demo_scheduled_discovery():
    """演示定时发现功能"""
    print("\n⏰ 演示定时发现功能")
    print("=" * 60)
    
    try:
        # 加载配置
        config = load_config()
        
        # 创建调度器
        scheduler = FreshTopicDiscoveryScheduler(config)
        
        # 种子关键词
        seed_keywords = [
            "Python编程",
            "数据分析"
        ]
        
        print(f"种子关键词: {seed_keywords}")
        print("注意: 定时发现会持续运行，按 Ctrl+C 停止")
        print()
        
        # 启动定时发现（间隔1小时，用于演示）
        print("🚀 启动定时发现任务（间隔1小时）...")
        scheduler.start_scheduled_discovery(seed_keywords, interval_hours=1)
        
    except KeyboardInterrupt:
        print("\n⏹️  用户中断，停止定时发现")
    except Exception as e:
        print(f"❌ 定时发现演示失败: {e}")
        import traceback
        traceback.print_exc()


def demo_email_notification():
    """演示邮件通知功能"""
    print("\n📧 演示邮件通知功能")
    print("=" * 60)
    
    try:
        # 加载配置
        config = load_config()
        
        # 创建发现小助手
        discovery = FreshTopicDiscovery(config)
        
        # 模拟新话题数据
        mock_new_topics = [
            {
                'topic_text': 'Python编程入门教程推荐',
                'source_keyword': 'Python编程',
                'search_source': '百度相关搜索',
                'search_round': 1,
                'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                'is_fresh': True
            },
            {
                'topic_text': '数据分析实战案例分享',
                'source_keyword': '数据分析',
                'search_source': '360搜索建议',
                'search_round': 1,
                'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                'is_fresh': True
            }
        ]
        
        print(f"模拟新话题: {len(mock_new_topics)} 个")
        for i, topic in enumerate(mock_new_topics, 1):
            print(f"  {i}. {topic['topic_text']}")
        
        print("\n📧 尝试发送邮件通知...")
        
        # 发送通知
        success = discovery.send_fresh_topic_notification(
            mock_new_topics,
            "Python编程,数据分析",
            1
        )
        
        if success:
            print("✅ 邮件通知发送成功！")
        else:
            print("❌ 邮件通知发送失败，请检查配置")
        
        # 清理资源
        discovery.cleanup()
        
    except Exception as e:
        print(f"❌ 邮件通知演示失败: {e}")
        import traceback
        traceback.print_exc()


def show_config_info():
    """显示配置信息"""
    print("⚙️  配置信息")
    print("=" * 60)
    
    try:
        config = load_config()
        
        # 显示新鲜需求发现配置
        discovery_config = config.get('fresh_topic_discovery', {})
        
        print("新鲜需求发现配置:")
        print(f"  启用状态: {discovery_config.get('enabled', False)}")
        print(f"  相似度阈值: {discovery_config.get('similarity_threshold', 0.8)}")
        print(f"  通知间隔: {discovery_config.get('notification_interval_hours', 24)} 小时")
        print(f"  每次通知最大话题数: {discovery_config.get('max_new_topics_per_notification', 10)}")
        
        # 邮件配置
        email_config = discovery_config.get('email', {})
        print(f"\n邮件配置:")
        print(f"  启用状态: {email_config.get('enabled', False)}")
        print(f"  SMTP服务器: {email_config.get('smtp_server', 'N/A')}")
        print(f"  SMTP端口: {email_config.get('smtp_port', 'N/A')}")
        print(f"  发件人: {email_config.get('username', 'N/A')}")
        print(f"  收件人: {email_config.get('to_emails', [])}")
        
        # 扩展字符配置
        expansion_chars = discovery_config.get('expansion_chars', [])
        print(f"\n扩展字符配置:")
        print(f"  字符数量: {len(expansion_chars)}")
        print(f"  字符列表: {expansion_chars}")
        
    except Exception as e:
        print(f"❌ 获取配置信息失败: {e}")


def main():
    """主函数"""
    print("🎯 新鲜需求发现小助手演示")
    print("=" * 80)
    
    try:
        # 显示配置信息
        show_config_info()
        
        # 演示单次发现
        demo_single_discovery()
        
        # 演示邮件通知
        demo_email_notification()
        
        print("\n" + "=" * 80)
        print("🎉 所有演示完成！")
        print("\n💡 使用说明:")
        print("  1. 修改 config/config.yaml 中的邮箱配置")
        print("  2. 运行 python fresh_topic_demo.py 进行演示")
        print("  3. 使用 FreshTopicDiscovery 类进行单次发现")
        print("  4. 使用 FreshTopicDiscoveryScheduler 类进行定时发现")
        print("  5. 新鲜话题会自动保存到数据库并发送邮件通知")
        
        # 询问是否运行定时发现
        print("\n⏰ 是否要演示定时发现功能？(y/n): ", end="")
        choice = input().strip().lower()
        
        if choice in ['y', 'yes', '是']:
            demo_scheduled_discovery()
        
    except Exception as e:
        print(f"\n❌ 程序执行失败: {e}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    main()
